import base64, json, random, conf
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance
from io import BytesIO


def generate_verification_code(code_len=4):
    width = 100
    height = 40
    image = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("arial.ttf", 30)

    code = ''
    for _ in range(code_len):
        char = random.choice([chr(random.randint(97, 122)), str(random.randint(0, 9))])
        code += char
        draw.text((8 + _ * 20, 5), char, font=font, fill=(0, 0, 0))

    for _ in range(random.randint(150, 200)):
        draw.point((random.randint(0, width), random.randint(0, height)), fill=(0, 0, 0))

    #模糊度调整
    #image = image.filter(ImageFilter.BLUR)
    image = image.filter(ImageFilter.SHARPEN)
    #image = image.filter(ImageFilter.SMOOTH)
    enhancer = ImageEnhance.Sharpness(image)
    image = enhancer.enhance(-1)

    buf = BytesIO()
    image.save(buf, "PNG")
    buf.seek(0)

    return buf.read(), code


# image, code = generate_verification_code()
# print(code)
# with open(code+'.png','wb') as f:
#     f.write(image)

con = conf.Redis.createcon(conf.Redis, 0)
for _ in range(31):
    image, code = generate_verification_code()
    dct = {'auth': code, 'data': base64.b64encode(image).decode('utf8')}
    con.set("code" + str(con.dbsize() + 1), json.dumps(dct))
